package com.hw.backapi.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hw.backapi.service.DoctorService;
import com.hw.backapi.service.IClientService;
import com.hw.backapi.service.IMemberService;
import com.hw.backapi.service.IinvitorService;
import com.hw.common.contants.CommonConstants;
import com.hw.common.contants.PageInfoContants;
import com.hw.common.enums.InvitorStatusEnum;
import com.hw.common.exception.BaseException;
import com.hw.common.utils.PhoneUtil;
import com.hw.model.common.PageInfo;
import com.hw.model.dto.PageInfoDTO;
import com.hw.model.dto.doctor.DetailQueryDTO;
import com.hw.model.dto.doctor.DoctorAuthDTO;
import com.hw.model.dto.doctor.DoctorDelDTO;
import com.hw.model.dto.doctor.DoctorSaveDTO;
import com.hw.model.dto.doctor.DoctorUpdateDTO;
import com.hw.model.entity.ClientPO;
import com.hw.model.entity.InvitorPO;
import com.hw.model.entity.MemberPO;
import com.hw.model.mapper.ClientMapper;
import com.hw.model.vo.doctor.DoctorListVO;
import com.hw.model.vo.doctor.DoctorPhoneListVO;
import com.hw.model.vo.member.MemberInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lipeng
 * @description 医生
 * @date 2023/3/8 13:21
 */
@Service
@Slf4j
public class DoctorServiceImpl implements DoctorService {
    @Autowired
    ClientMapper clientMapper;

    @Autowired
    IClientService clientServiceImpl;

    @Autowired
    IinvitorService invitorServiceImpl;

    @Autowired
    IMemberService memberServiceImpl;

    @Override
    public PageInfo<DoctorListVO> detailListPage(DetailQueryDTO detailQueryDTO) {
        if( detailQueryDTO.getPageNum() < 1 ){
            detailQueryDTO.setPageNum(PageInfoContants.PAGE_NUM);
            detailQueryDTO.setPageSize(PageInfoContants.PAGE_SIZE);
        }
        PageInfo<DoctorListVO> result = new PageInfo<>(detailQueryDTO.getPageNum(),
                detailQueryDTO.getPageSize());

        //查询数据库
        Page<DoctorListVO> page = new Page<>(detailQueryDTO.getPageNum(), detailQueryDTO.getPageSize());
        Page<DoctorListVO> doctorListPage = clientMapper.getDoctorList(page,detailQueryDTO);
        List<DoctorListVO> doctorList = doctorListPage.getRecords();
        if(CollectionUtil.isEmpty(doctorList)){
            result.setList(Collections.emptyList());
            return result;
        }

        //获取用户手机号
//        List<String> phoneList = doctorList.stream().map(DoctorListVO::getCellphone).collect(Collectors.toList());

        doctorList.stream().forEach(doctorListVO -> {
            MemberPO memberMasterInfo = memberServiceImpl.getMemberMasterInfo(doctorListVO.getId());
            //不为空，说明有可能有成员
            if( null != memberMasterInfo ){
                List<MemberInfoVO> memberList =
                        memberServiceImpl.getMemberList(memberMasterInfo.getFid());
                if( CollectionUtil.isNotEmpty(memberList) ){
                    memberList.stream()
                            .filter(memberInfoVO -> !memberInfoVO.getId().equals(memberMasterInfo.getId()))
                            .forEach(memberInfoVO -> {
                                doctorListVO.getAuthorizationList().add(memberInfoVO.getCellphone());
                            });
                    doctorListVO.setAuthorization(CollectionUtil.join(doctorListVO.getAuthorizationList(),","));
                }
            }
        });

        //获取邀请列表
//        List<InvitorPO> invitorList = invitorServiceImpl.getInvitorList(phoneList, InvitorStatusEnum.AGREE.getCode());
//        if( CollectionUtil.isNotEmpty(invitorList) ){
//            //邀请人手机号 -> 被邀请信息
//            Map<String, List<InvitorPO>> invitorMap =
//                    invitorList.stream().collect(Collectors.groupingBy(InvitorPO::getInvitor));
//
//            doctorList.forEach(doctorListVO -> {
//                List<InvitorPO> invitorPOList = invitorMap.get(doctorListVO.getCellphone());
//                if( CollectionUtil.isNotEmpty(invitorPOList) ){
//                    invitorPOList.forEach(invitorPO -> {
//                        doctorListVO.getAuthorizationList().add(invitorPO.getCellphone());
//                    });
//                }
//                doctorListVO.setAuthorization(CollectionUtil.join(doctorListVO.getAuthorizationList(),","));
//            });
//
//        }
        result.setPage(doctorListPage.getTotal(),doctorList);

        return result;
    }

    @Override
    public List<DoctorPhoneListVO> detailPhoneList(DetailQueryDTO detailQueryDTO) {
        List<DoctorPhoneListVO> doctorList = clientMapper.getDoctorPhoneList(detailQueryDTO);
        if( CollectionUtil.isEmpty(doctorList) ){
            return Collections.emptyList();
        }

        return doctorList;
    }

    @Override
    public void addDoctor(DoctorSaveDTO doctorSaveDTO) {
        String phone = PhoneUtil.replacePhone(doctorSaveDTO.getPhone());

        List<ClientPO> clientInfo = clientServiceImpl.getClientInfo(Collections.singletonList(phone));
        if( CollectionUtil.isNotEmpty(clientInfo) ){
            throw new BaseException("Doctor already exists");
        }

        doctorSaveDTO.setPhone(phone);
        boolean res = clientServiceImpl.createClient(doctorSaveDTO.getPhone(), "123456", 2);
        if( !res ){
            throw new BaseException("Created failed");
        }
    }

    @Override
    public void delDoctor(DoctorDelDTO doctorDelDTO) {
        ClientPO clientPO = clientMapper.selectById(doctorDelDTO.getDoctorId());
        if( null == clientPO ){
            throw new BaseException("delDoctor:user does not exist");
        }
        if( !clientPO.getIsDoctor().equals(CommonConstants.DOCTOR) ){
            throw new BaseException("delDoctor:The user is not a doctor");
        }
        try {
            log.info("删除的医生数据，id:{},data:{}",doctorDelDTO.getDoctorId(),clientPO);
            clientMapper.deleteById(doctorDelDTO.getDoctorId());
        }catch (Exception e){
            throw new BaseException("Failed to delete,please try again");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDoctor(DoctorUpdateDTO doctorUpdateDTO) {
        ClientPO clientPO = clientMapper.selectById(doctorUpdateDTO.getId());
        if( null == clientPO ){
            throw new BaseException("updateDoctor: user does not exist");
        }
        if( !clientPO.getIsDoctor().equals(CommonConstants.DOCTOR) ){
            throw new BaseException("updateDoctor: The user is not a doctor");
        }

        clientPO.setUpdatedAt(new Date());
        clientPO.setCellphone(doctorUpdateDTO.getPhone());
        try{
            clientMapper.updateById(clientPO);
//            invitorServiceImpl.doInvitor(doctorUpdateDTO.getAuthorizationList(),9999L,clientPO);
        }catch (BaseException baseException){
            throw baseException;
        } catch (Exception e){
            e.printStackTrace();
            throw new BaseException("updateDoctor: Failed to update doctor data");
        }
    }

    @Override
    public void doctorAddAuth(DoctorAuthDTO doctorAuthDTO) {
        ClientPO clientPO = clientMapper.selectById(doctorAuthDTO.getId());
        if( null == clientPO ){
            throw new BaseException("user does not exist");
        }
        if( !clientPO.getIsDoctor().equals(CommonConstants.DOCTOR) ){
            throw new BaseException("The user is not a doctor");
        }
        try{
            invitorServiceImpl.doInvitor(doctorAuthDTO.getAuth(),doctorAuthDTO.getDoctorName(),clientPO);
        }catch (BaseException baseException){
            throw baseException;
        } catch (Exception e){
            e.printStackTrace();
            throw new BaseException("Send authorization failed，please retry");
        }
    }

    @Override
    public void doctorCancelAuth(DoctorAuthDTO doctorAuthDTO) {
        ClientPO clientPO = clientMapper.selectById(doctorAuthDTO.getId());
        if( null == clientPO ){
            throw new BaseException("updateDoctor: user does not exist");
        }
        if( !clientPO.getIsDoctor().equals(CommonConstants.DOCTOR) ){
            throw new BaseException("updateDoctor: The user is not a doctor");
        }
        try{
            invitorServiceImpl.doDelInvitor(doctorAuthDTO.getAuth(),clientPO);
        }catch (BaseException baseException){
            throw baseException;
        } catch (Exception e){
            e.printStackTrace();
            throw new BaseException("cancel authorization failed，please retry");
        }
    }
}
